#include "TcpConnection.h"

TcpConnection::TcpConnection(EventLoop *loop, const string &name, int sockfd,
                                   const InetAddress &localAddr, const InetAddress &peerAddr)
    : _loop(loop)
    , _name(name)
    , _state(kConnecting)
    , _socket(std::make_unique<Socket>(sockfd))
    , _channel(std::make_unique<Channel>(loop, sockfd))
    , _localAddr(localAddr)
    , _peerAddr(peerAddr)
{
    cout << "TcpConnection created: " << name << " fd=" << sockfd << "\n";
    _channel->setReadCallback(std::bind(&TcpConnection::handleRead, this));
    _channel->setWriteCallback(std::bind(&TcpConnection::handleWrite, this));
    _channel->setErrorCallback(std::bind(&TcpConnection::handleError, this));
}

TcpConnection::~TcpConnection()
{
    std::cerr << "TcpConnection destroyed: " << _name << "\n";
    assert(_state == kDisconnected);
}

void TcpConnection::handleRead()
{
    char buf[65536];
    ssize_t n = ::read(_channel->fd(), buf, sizeof(buf));
    if(n > 0)
    {
        _messageCallback(shared_from_this(), string(buf, n));
    }
    else if(n == 0)
    {
        std::cerr << "TcpConnection::handleRead: connection closed by peer\n";
        handleClose();
    }
    else
    {
        perror("TcpConnection::handleRead read");
        handleError();
    }
}

void TcpConnection::handleWrite()
{
    // 处理写事件
    // 这里可以添加发送数据的逻辑
}

void TcpConnection::handleClose()
{
    _loop->assertInLoopThread();
    std::cerr << "TcpConnection::handleClose: connection closed\n";
    assert(_state == kConnected);
    _channel->disableAll();
    _closeCallback(shared_from_this());
}
void TcpConnection::handleError()
{
    int err = errno;
    std::cerr << "TcpConnection::handleError: error occurred, errno=" << err << "\n";
    // 处理错误
    // 可以添加更多的错误处理逻辑
}

void TcpConnection::connectDestroyed()
{
    _loop->assertInLoopThread();
    std::cerr << "TcpConnection::connectDestroyed: connection destroyed\n";
    assert(_state == kConnected);
    setState(kDisconnected);
    _channel->disableAll();
    _loop->removeChannel(_channel.get());
}

void TcpConnection::connectEstablished()  
{
    _loop->assertInLoopThread();
    assert(_state == kConnecting);
    setState(kConnected);
    _channel->enableReading(); // 启用读事件
    std::cerr << "TcpConnection::connectEstablished: connection established\n";
    
    // 调用连接建立回调
    _connectCallback(shared_from_this());
}